package com.example.permission.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.example.common.enetiy.AccessLog;
import com.example.common.enetiy.User;
import com.example.common.mapper.AccessLogMapper;
import com.example.common.service.UserService;
import com.example.common.utils.JwtUtils;
import com.example.common.utils.RedisUtils;
import com.example.permission.mapper.SystemUserRoleMapper;
import com.example.permission.model.req.LoginDTO;
import com.example.permission.model.req.RegisterDTO;
import com.example.permission.service.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/10/30 21:22
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    private final UserService userService;
    private final RedisUtils redisUtils;
    private final AccessLogMapper accessLogMapper;
    private final SystemUserRoleMapper systemUserRoleMapper;

    @Override
    public String login(LoginDTO loginDTO, AccessLog accessLog) {
        // 查询用户
        User user = userService.queryUserByLogin(loginDTO.getUsername(), loginDTO.getPassword());
        // 生成token
        String sessionId = UUID.randomUUID().toString();
        String token = JwtUtils.generateToken(user.getUserId(), user.getUsername(), sessionId);
        redisUtils.set("sys:login:" +  sessionId, token, 1L, TimeUnit.DAYS);

        accessLog.setUserId(user.getUserId());
        this.loginLog(accessLog);
        return token;
    }

    @Override
    public void register(RegisterDTO registerDTO) {
        String userId = userService.registerUser(registerDTO.getUsername(), registerDTO.getPassword());
        systemUserRoleMapper.saveUserRole(userId, "3cbbbd3c-48b3-4581-bf58-4591812433a2");
    }

    @Override
    public void logout() {

    }

    public void loginLog(AccessLog accessLog) {
        System.out.println(JSONObject.toJSONString(accessLog));
        accessLogMapper.addLoginLog(accessLog);
    }
}
